"""
 (继续上面的练习) 模拟用户登录:
     5个同学的姓名,账号和密码(加密后的),保存在一个文件上;
     系统提示,请输入登录同学姓名, 正确后,请输入账号, 正确后,提示请输入密码（输入明文）;  如果都正确,打印提示, 您登录成功(失败);
"""
import json
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64
from Crypto import Random


def find_name():
    while True:
        name = input("请输入登录同学姓名:")
        if name not in data:
            print("name not found")
        else:
            return name

def verify_account(name):
    while True:
        account = input("请输入账号:")
        if account != data[name]['account']:
            print("incorrect account")
        else:
            return


def decrypt(encrypted_pwd):
    with open("rsa.private.pem", mode="r") as f:
        prikey = f.read()
        rsa_pk = RSA.importKey(prikey)
        rsa = PKCS1_v1_5.new(rsa_pk)
        result = rsa.decrypt(base64.b64decode(encrypted_pwd), gen_random)
        # print("this is result:",result.decode("utf-8"))
        return result.decode("utf-8")


def verify_pwd(name):
    encrypted_pwd = data[name]['pwd']
    correct_pwd = decrypt(encrypted_pwd)
    # print("correct_pwd:", correct_pwd)
    while True:
        input_pwd = input("请输入密码（输入明文）:")
        if input_pwd == correct_pwd:
            print("登录成功")
            break
        else:
            print("登录失败")


if __name__ == '__main__':
    gen_random = Random.new
    with open('3.json') as f:
        data = json.load(f)
        # print(type(data))
        # print(data)
        name = find_name()
        verify_account(name)
        verify_pwd(name)



